<template>
  <!-- 消息列表 -->
  <div id="msgList" class="message_list">
    <ul id="msgUl">
      <li v-for="(item, index) in messageArr" :key="index">
        <div class="name_time" style="color:#37D07B" v-if="item.self">{{item.name}} {{item.time}}</div>
        <div class="name_time" v-if="!item.self">{{item.name}} {{item.time}}</div>
        <div class="msg_content">{{item.content}}</div>
      </li>
    </ul>
    <div class="msg_input">
      <el-input v-model="msgContent" placeholder="请输入内容" @keyup.enter.native="sendMsg"></el-input>
      <el-button type="primary" @click="sendMsg">发送</el-button>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      messageArr: [],
      msgContent: ''
    }
  },
  props: {
    msg: { // 收到的消息
      type: Object
    },
    selfName: { // 自己名字
      type: String
    }
  },
  watch: {
    msg (val) {
      switch (val.msgType) {
        case 'text':
          this.getTextMsg(val)
          break;
        default:
          break;
      }
    }
  },
  methods: {
    /** 发送消息 */
    sendMsg () {
      if (!this.msgContent) {
        this.$notify.error({
          title: '提示',
          message: '请输入消息内容！'
        })
        return
      }
      this.umvideo.sendMsg({
        msgid: this.$GetRandomString(10),
        msgType: 'text',
        msg: this.msgContent
      })
      .then(res => {
        if (res.code != 200) {
          this.$notify.error({
            title: '提示',
            message: '消息发送失败，请重试！'
          })
          return
        }
        this.messageArr.push({name: this.selfName, content: this.msgContent, time: this.$dateFormat("YYYY-mm-dd HH:MM:SS", new Date()), self: true})
        this.msgContent = ''
        this.$nextTick(() => document.getElementById('msgUl').scrollTop = document.getElementById('msgUl').scrollHeight)
      })
    },
    /** 收到文字消息 */
    getTextMsg (val) {
      let time = this.$dateFormat("YYYY-mm-dd HH:MM:SS", new Date(val.msgTime))
      this.messageArr.push({name: val.peerName, content: val.msg, time: time, self: false})
    }
  }
}
</script>

<style scoped lang="scss">
.message_list {
  height: calc(100% - 66px);
  padding: 15px 20px 0 20px;
  position: relative;
  ul {
    height: calc(100% - 60px);
    overflow-y: auto;
    li {
      font-size: 14px;
      margin-top: 20px;
      .name_time {
        color: #2E9CF1;
      }
      .msg_content {
        margin-top: 5px;
      }
    }
    li:first-child {
      margin: 0;
    }
  }
  .msg_input {
    display: flex;
    position: absolute;
    bottom: 10px;
    left: 20px;
    right: 20px;
    >>> .el-button {
      margin-left: 10px;
    }
  }
}
</style>